package com.example.bookstore.dao.impl;

import com.example.bookstore.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao<T> {
    private QueryRunner qr = new QueryRunner();

    public int update(String sql,Object... args) throws SQLException {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            int update = qr.update(connection, sql, args);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtils.close(connection);
        }

    }

    public T querySingle(String sql, Class<T> clazz, Object... params) throws SQLException {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.query(connection, sql, new BeanHandler<T>(clazz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.close(connection);
        }
    }

    public List<T> queryMulti(String sql, Class<T> clazz, Object... params) throws SQLException {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.close(connection);
        }
    }

    public Object queryScalar(String sql, Object... params) throws SQLException {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.query(connection,sql,new ScalarHandler(),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.close(connection);
        }
    }
}
